package com.flannery.leetcode

fun main(){
    println("两数之和")
    /*
    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]
     */
    twoSum2(intArrayOf(3,2, 4, 2,7,11,15), 9)
}

//方法一：两遍哈希表
fun twoSum(nums:IntArray, target:Int):IntArray{
    var hashMapOf = hashMapOf<Int, Int>()
    nums.forEachIndexed { index, i ->
        hashMapOf.put(i, index)
    }
    nums.forEachIndexed { index, i ->
        var complement = target - nums[index]
        if(hashMapOf.containsKey(complement) && hashMapOf.get(complement)!=i) {
            hashMapOf.get(complement)?.let {
                intArrayOf(i, it)
            }
        }
    }
    return intArrayOf()
}

fun twoSum2(nums:IntArray, target:Int){
    var map = hashMapOf<Int, Int>()
    nums.forEachIndexed { index, value ->
        var complement = target - value
        if(map.containsKey(complement)) {
            map[complement]?.let {
                //intArrayOf(it, index)
                println("$index - $it")
                return
            }
        }
        map.put(value, index)
    }
}

